import axios from 'axios'
import {MessageBox, Message} from 'element-ui'
import {getToken} from '@/utils/auth'

console.log(process.env.VUE_APP_BASE_API + '/api')
const request = axios.create({
  baseURL: process.env.VUE_APP_BASE_API + '/api', // 基本路由
  timeout: 5000, // 超时时间
  headers: {
    'Content-Type': 'application/json'
  }
})

// 请求拦截器
request.interceptors.request.use(
  config => {
    const token = getToken()
    if (token) {
      config.headers['Authorization'] = 'Bearer ' + token
    }
    return config
  },
  error => {
    console.log('请求拦截器，请求错误：', error)
    return Promise.reject(error)
  }
)

// 响应拦截器
request.interceptors.response.use(
  response => {
    return response.data
  },
  error => {
    //处理网络错误
    let msg = ''
    console.log('响应拦截器，响应错误：', error)
    let status = error.response.status;
    switch (status) {
      case 401:
        msg = 'token过期！'
        break
      case 403:
        msg = '无权操作权限！'
        break
      case 404:
        msg = '请求地址错误！'
        break
      case 500:
        msg = '服务器出现问题！'
        break
      default:
        msg = '无网络'
    }
    Message({
      type: 'error',
      message: msg
    })
    return Promise.reject(error)
  }
)

export default request
